package com.example.wj.service.impl;

import com.example.wj.dao.CategoryDao;
import com.example.wj.dto.BookDto;
import com.example.wj.entity.Book;
import com.example.wj.dao.BookDao;
import com.example.wj.entity.Category;
import com.example.wj.service.BookService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookDao bookDao;

    @Autowired
    private CategoryDao categoryDao;

    @Override
    public Book insertOrUpdate(BookDto bookDto) {
        Book book = new Book();
        BeanUtils.copyProperties(bookDto, book);
        //book.setCid(bookDto.getCategory().getId());

        if (bookDto.getId() != null) {
            bookDao.update(book);
        } else {
            bookDao.insert(book);
        }
        return book;
    }

    @Override
    public boolean deleteById(Integer id) {
        bookDao.deleteById(id);
        categoryDao.deleteById(id);
        return this.bookDao.deleteById(id) > 0;
    }

    @Override
    public BookDto queryById(Integer id) {
        BookDto dto = new BookDto();

        Book book = bookDao.queryById(id);
        Category category = categoryDao.queryById(book.getId());
        dto.setCategory(category);
        return dto;
    }

    @Override
    public Page<Book> queryByPage(Book book, PageRequest pageRequest) {
        long total = this.bookDao.count(book);
        return new PageImpl<>(this.bookDao.queryAllByLimit(book, pageRequest), pageRequest, total);
    }

    @Override
    public List<BookDto> queryList(String keyWord) {
        return bookDao.queryList(keyWord);
    }
}
